#include "core/triangle.hpp"

void Triangle::getData(Point* v0, Point* v1, Point* v2) const
{
  *v0 = parent->verts[parent->inds[index*3+0]];
  *v1 = parent->verts[parent->inds[index*3+1]];
  *v2 = parent->verts[parent->inds[index*3+2]];
}

//BORROWED FROM PBRT
bool isectTriangle(const Triangle& t, const Ray& r, Intersection* isect, const float maxt)
{
  Point p1,p2,p3;
  t.getData(&p1,&p2,&p3);
  Vector e1 = p2-p1;
  Vector e2 = p3-p1;
  Vector s1 = cross(r.d, e2);
  float divisor = dot(s1,e1);

  if(divisor == 0.f) return false;
  float invDiv = 1.f/divisor;

  Vector d = r.o - p1;
  float b1 = dot(d,s1) * invDiv;
  if(b1 < 0.f || b1 > 1.f) return false;
  
  Vector s2 = cross(d,e1);
  float b2 = dot(r.d, s2) * invDiv;
  if(b2 < 0.f || b1+b2 > 1.f) return false;

  float tt = dot(e2,s1) * invDiv;
  if(tt > maxt || tt<0);

  if(isect == NULL) return true;

  *isect = (Intersection){r(tt), t.n, tt};
  return true;
}
  
